var from_point;
var to_point;
$(document).ready(function(){
    var screenX=$(window).width();
    var screenH=$(window).height();
    var screenY=$(document).height();
    //判断2个DIV遮掩层的宽度和高度
    var lWidth=$("#twoKeep_sceen").width();
    var lHeight=$("#twoKeep_sceen").height();
    var loadHeight=$("#mappositoon").height();
    var loadWidth=$("#mappositoon").width();
    var logWidth=$("#box_sceen").width();
    var logHeight=$("#box_sceen").height();

    var threeHeight=$("#threeKeep_sceen").height();
    var tboxHeight=$("#threebox_sceen").height();
    //判断2个DIV遮掩层的lef和top值
    var iLeft=parseInt((screenX-lWidth)/2)+"px";
    var iTop=parseInt((screenH-lHeight)/2)+"px";
    var logLeft=parseInt((screenX-logWidth)/2)+"px";
    var logTop=parseInt((screenH-logHeight)/2)+"px";
    var loadLeft=parseInt((screenX-loadWidth)/2)+"px";
    var loadTop=parseInt((screenH-loadHeight)/2)+"px";

    var threeTop=parseInt((screenH-threeHeight)/2)+"px";
    var tboxTop=parseInt((screenH-tboxHeight)/2)+"px";
    //------------------------------------------------------------------------------
    /****第一个div遮掩层***///
    function showKeep_div(){
        twoWidth = (screenX < lWidth) ? lWidth : '100%';
        $("#keep_sceen").css({
            "width":twoWidth,
            "height":screenY+"px"
        }).show();
        showKeep_sceen();
        showbox_sceen();
    }

    /****第二个div遮掩层***///
    function showKeep_sceen(){
        $("#twoKeep_sceen").show().css({
            "position":'fixed',
            "left":iLeft,
            "top":iTop
        });
    }

    /****第map加载div遮掩层***///
    function showmap_sceen(){
        $("#mappositoon").show().css({
            "position":'fixed',
            "left":loadLeft,
            "top":loadTop
        });
    }

    /****div显示弹出层***///
    function showbox_sceen(){
        $("#box_sceen").show().css({
            "position":'fixed',
            "left":logLeft,
            "top":logTop
        });
    }
    //------------------------------------------------------------------------------
    /****调用公交线路遮掩层***///
    function threeKeep_div(){
        tWidth = (screenX < lWidth) ? lWidth : '100%';
        $("#keep_sceen").css({
            "width":tWidth,
            "height":screenY+"px"
        }).show();
        threeKeep_sceen();
        tbox_sceen();
    }

    function threeKeep_sceen(){
        $("#threeKeep_sceen").show().css({
            "position":'fixed',
            "left":iLeft,
            "top":threeTop
        });
    }

    function tbox_sceen(){
        $("#threebox_sceen").show().css({
            "position":'fixed',
            "left":logLeft,
            "top":tboxTop
        });
    }
    //------------------------------------------------------------------------------
    //窗口压缩事件
    $(window).resize(function(){
        /**窗口默认时定位的位置**/
        screenX=$(window).width();
        screenH=$(window).height();
        iLeft=parseInt((screenX-lWidth)/2)+"px";
        iTop=parseInt((screenH-lHeight)/2)+"px";
        logLeft=parseInt((screenX-logWidth)/2)+"px";
        logTop=parseInt((screenH-logHeight)/2)+"px";

        threeTop=parseInt((screenH-threeHeight)/2)+"px";
        tboxTop=parseInt((screenH-tboxHeight)/2)+"px";
        twoWidth = (screenX < lWidth) ? '1200px' : '100%';
        //判断对象是不是显示
        if($('#keep_sceen').is(':visible')){
            $("#keep_sceen").css({
                "width":twoWidth,
                "height":screenY+"px"
            })
            if($('#box_sceen').is(':visible')){
                showKeep_sceen();
                showbox_sceen();
            }
            else if($('#threebox_sceen').is(':visible')){
                threeKeep_sceen();
                tbox_sceen();
            }
        }
    });

    //------------------------------------------------------------------------------

    //点击身边工作默认调用
    if(set_seesion=='no'){
        showKeep_div();
        var areapos=mypos.split(',');
        getMaps(areapos[0],areapos[1],areapos[2]);
    }
    //弹出框
    $('#popupBox').click(function(){
        showKeep_div();
        var areapos=mypos.split(',');
        getMaps(areapos[0],areapos[1],areapos[2]);
    });
    //点击定位按钮
    $(".mleft").find('li a').click(function (){
        var areaName=$(this).attr('ref').split(',');
        getMaps(areaName[0],areaName[1],areaName[2]);
        $('#position').val($(this).attr('ref'));
    });
    //点击确定按钮
    $(".determine").click(function (){
        $('#twoKeep_sceen').hide();
        $('#box_sceen').hide();
        showmap_sceen();   //显示加载地图的信息框
        $.ajax({
            type: "post",
            url: "/job?map_show=1",
            data:{position:$('#position').val(),_token:_token},
            success : function(data){
                location.href='/job?map_show=1';
            }
        });
    });
    //点击取消按钮
    $(".cancel").click(function (){
        $('#keep_sceen').hide();
        $('#twoKeep_sceen').hide();
        $('#box_sceen').hide();
    });

    //--------------------------------------------------------------------------------------------------------------


    //---------------------公交线路和驾车线路-----------------------------------------------------------------------------------------
    //点击关闭按钮
    $("#close").click(function (){
        $('#keep_sceen').hide();
        $('#threeKeep_sceen').hide();
        $('#threebox_sceen').hide();
    });

    //点击公交位置弹出
    $(".mapshow").click(function (){
        threeKeep_div();
        $('.bus').show();
        $('.car').hide();
        $(".bright").find('li').each(function (index){
            $(".bright").find('li').eq(0).removeClass('g_title');
            $(".bright").find('li').eq(1).addClass('g_title');
        });

        from_point=$('#position').val();
        to_point=$(this).attr('data-id');
        busMap($(this));
    });

    //点击公交位置弹出
    $(".bright").find('li').each(function (index){
        $(this).click(function(){
            $(this).removeClass('g_title').siblings().addClass('g_title');
            if(index == 0 ){
                $('.bus').show();$('.car').hide();
            }else{
                $('.bus').hide();$('.car').show();
                jiache($(this));
                /*if($('#l-result').html() == '' || $('#l-result').html() == 'undefined'){
                 jiache(this);
                 }*/
            }
        });
    });
});

//--------------------------------------------------------------------------------------------------------------

function busMap(dom){
    var areapos1=from_point.split(',');
    var areapos2=to_point.split(',');
    driveMap(areapos1[0],areapos1[1],areapos1[2],areapos2[0],areapos2[1],areapos2[2],-1,dom,1);
}

function jiache(dom){
    var areapos1=from_point.split(',');
    var areapos2=to_point.split(',');
    driveMap(areapos1[0],areapos1[1],areapos1[2],areapos2[0],areapos2[1],areapos2[2],-1,dom,2);
}

//绘制地公交线路驾车线路函数
function driveMap(f_lng,f_lat,f_position,c_lng,c_lat,c_position,num,dom,type){
    var f_point=new BMap.Point(f_lng,f_lat);
    var c_point=new BMap.Point(c_lng,c_lat)
    map = new BMap.Map("mapshow2", { minZoom: 12}); //地图显示位置
    map.enableScrollWheelZoom();					//鼠标大小缩放
    map.enableKeyboard();							//启用鼠标双击放大,默认启用(可不写)
    map.addControl(new BMap.NavigationControl());	//显示大小滚轮条
    map.centerAndZoom(f_point, 15);		//设置中心店

    if(type==1){ //公交路线
        var transit = new BMap.TransitRoute("台州市");
        transit.setSearchCompleteCallback(function(results){
            if(transit.getStatus() == BMAP_STATUS_SUCCESS){	//利用getStatus()检测是否检索成功
                if(num==-1){
                    var s = [];
                    for (i = 0; i < results.getNumPlans(); i ++){	//得到几条公交线路方案
                        var luxian = '<div class="busPosition"><p>' + results.getPlan(i).getDescription(false).replace(/\d\.\s*/g,'<span></span>').replace(/(，\s*)?步行/g,'<p><span class="walk">步行</span>')
                                .replace(/，到达/g,'<span class="arrivals">到达</span>').replace(/，乘坐/g,'</p><p><span class="ride">乘坐</span>') + '</p></div>';
                        if(i==0){
                            s.push('<div class="luxian" onclick="driveMap('+f_lng+','+f_lat+',\''+f_position+'\','+c_lng+','+c_lat+',\''+c_position+'\','+i+',this,'+type+')"><div class="statrLuxian"><span>'+f_position+'</span></div>'+luxian+'<div class="endLiuxian"><span>'+c_position+'</span></div></div>');
                        }else{
                            s.push('<div class="luxian selectLuxian" onclick="driveMap('+f_lng+','+f_lat+',\''+f_position+'\','+c_lng+','+c_lat+',\''+c_position+'\','+i+',this,'+type+')"><div class="statrLuxian"><span>'+f_position+'</span></div>'+luxian+'<div class="endLiuxian"><span>'+c_position+'</span></div></div>');
                        }
                    }
                    $('#r-result').html(s.join(''));
                }
                var num1=num;
                if(num==-1) num1=0;
                if(num!=-1) $(dom).removeClass('selectLuxian').siblings("div").addClass('selectLuxian');
                var firstPlan = results.getPlan(num1);
                //绘制步行线路
                for (var i = 0; i < firstPlan.getNumRoutes(); i ++){
                    var walk = firstPlan.getRoute(i);
                    if (walk.getDistance(false) > 0){
                        map.addOverlay(new BMap.Polyline(walk.getPath(), {strokeColor: "green"}));
                    }
                }
                // 绘制公交线路
                for (i = 0; i < firstPlan.getNumLines(); i ++){
                    var line = firstPlan.getLine(i);
                    map.addOverlay(new BMap.Polyline(line.getPath()));
                }
            }else{
                $('#r-result').html('<div style="text-align:center; font-size:15px; padding:20px;font-family:\'微软雅黑\'">无法查询公交路线..</div>');
            }
        })
        transit.search(f_point, c_point);
        map.addOverlay(new BMap.Marker(f_point, {icon: new BMap.Icon("/default/images/index/icon_start.gif", new BMap.Size(29, 37))}));
        map.addOverlay(new BMap.Marker(c_point, {icon: new BMap.Icon("/default/images/index/icon_end.gif", new BMap.Size(29, 37))}));
    }else{	//驾车路线
        var driving = new BMap.DrivingRoute(map, {renderOptions : {map : map,autoViewport:true},
            onSearchComplete: function(results){
                if (driving.getStatus() == BMAP_STATUS_SUCCESS){	//利用getStatus()检测是否检索成功
                    var plan = results.getPlan(0);					// 获取方案
                    var route = plan.getRoute(0);					// 获取方案的驾车线路
                    var s = [];										// 获取每个关键步骤，并输出到页面
                    for (var i = 0; i < route.getNumSteps(); i ++){
                        var step = route.getStep(i);
                        s.push('<div class="directions">'+(i + 1) + ". " + step.getDescription()+'</div>');
                    }
                    $('#l-result').html('<div class="luxian carDirections"><div class="statrLuxian"><span>'+f_position+'</span></div>'+s.join("")+'<div class="endLiuxian"><span>'+c_position+'</span></div></div>');
                }else{
                    $('#l-result').html('<div style="text-align:center; font-size:15px; padding:20px;font-family:\'微软雅黑\'">无法查询驾车路线..</div>');
                }
            }
        });
        driving.search(f_point, c_point);
    }
}

//绘制地图定位函数
function getMaps(lng,lat,position) {
    var map = new BMap.Map("mapshow");					//显示位置
    map.enableScrollWheelZoom();					//鼠标大小缩放
    map.addControl(new BMap.NavigationControl());	//显示大小滚轮条
    var point = new BMap.Point(lng,lat);
    map.centerAndZoom(point, 15);					//以15的格式显示地图中心店

    var markerls = new BMap.Marker(point);				//新建标注
    var infoWindow = new BMap.InfoWindow("<span style=\"font-size:14px;\">当前位置:"+position+"<br><span style=\"font-size:12px; line-height:24px;\">(提示:任意点击地图,选择您的位置)</span></span>");
    map.openInfoWindow(infoWindow,point);			//默认时，显示窗口信息
    //$('#position').val(lng+','+lat+','+position);

    markerls.addEventListener("click", function() {
        map.openInfoWindow(infoWindow,point);
    });												//点击标注点时显示窗口信息

    markerls.enableDragging(true); 					//启用地图鼠标拖拽
    map.addOverlay(markerls);						//添加标注点在地图上

    //创建地理编码
    var geoc = new BMap.Geocoder();
    map.addEventListener('click', function(e) {		//点击地图任意位置事件触发
        map.removeOverlay(markerls);				//点击地图任意点时，删除对象地图上的markerls标注点
        markerls = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat));  //新建地图markerls
        map.addOverlay(markerls);					//添加新的标注点markerls

        var pt = e.point;							//获取新的经纬度
        geoc.getLocation(pt, function(rs){			//根据坐标得到地址描述
            var addComp = rs.addressComponents;
            var address=addComp.district +  addComp.street+ addComp.streetNumber;	//获取地址
            //var address=rs.address;					//获取地址
            $('#position').val(pt.lng+','+pt.lat+','+address);
            var infoWindow_new = new BMap.InfoWindow("<span style=\"font-size:14px;\">当前位置:"+address+"<br><span style=\"font-size:12px; line-height:24px;\">(提示:任意点击地图,选择您的位置)</span></span>");
            map.openInfoWindow(infoWindow_new,new BMap.Point(pt.lng, pt.lat));
        });
    });
}

